package cn.edu.cdut.service;

import cn.edu.cdut.dao.AdminInfoDao;
import cn.edu.cdut.dao.StudentInfoDao;
import cn.edu.cdut.model.AdminInfo;
import cn.edu.cdut.dto.MyRes;
import cn.edu.cdut.model.StudentInfo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * Author  kobe
 * Created on 2017-05-26-14:40
 */
@Service
public class LoginService {

        @Autowired
        private AdminInfoDao adminInfoDao;

        @Autowired
        private StudentInfoDao studentInfoDao;


        //登录
        @Transactional
        public MyRes login(String userId, String password) {
                if (userId.contains("admin")) {/*根据教职工号与学号的差别进行判断，这里只是个例子*/
                        AdminInfo adminInfo = adminInfoDao.findByAdminId(userId);
                        if (adminInfo == null) {
                                return new MyRes(201, "帐号错误或不存在！", null);
                        } else if ( ! adminInfo.getPassword().equals(password)) {
                                return new MyRes(201, "密码错误！", null);
                        }
                        ObjectMapper mapper = new ObjectMapper();
                        String adminStr = null;
                        try {
                                adminStr = mapper.writeValueAsString(adminInfo);
                        } catch (JsonProcessingException e) {
                                e.printStackTrace();
                        }
                        return new MyRes(200, "登陆成功！", adminStr);
                } else {
                        StudentInfo studentInfo = studentInfoDao.findByStuId(userId);
                        if (studentInfo == null) {
                                return new MyRes(201, "帐号错误！", null);
                        } else if ( ! studentInfo.getPassword().equals(password)) {
                                return new MyRes(201, "密码错误！", null);
                        }
                        ObjectMapper mapper = new ObjectMapper();
                        String stuStr = null;
                        try {
                                stuStr = mapper.writeValueAsString(studentInfo);
                        } catch (JsonProcessingException e) {
                                e.printStackTrace();
                        }
                        return new MyRes(200, "登陆成功！", stuStr);
                }
        }
}
